package cn.tedu._05mvcboot02.exception;

import cn.tedu._05mvcboot02.common.response.JsonResult;
import cn.tedu._05mvcboot02.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.message.Message;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import sun.rmi.runtime.Log;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalAccessException ex){
        String messaage= ex.getMessage();
        log.error("IllegalArgumentException:"+messaage);
        return new JsonResult(StatusCode.OPERATION_FAILED, messaage);



    }

    @ExceptionHandler
    public JsonResult doHandle(BindException ex){

        String message = ex.getFieldError().getDefaultMessage();
        log.error("BindException:" + message);
        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        //获取异常提示消息
        String message = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:" + message);
        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }


    @ExceptionHandler
    public JsonResult doHanleRuntimeException(RuntimeException ex){
        String message = ex.getMessage();
        log.error("RuntimeException:" + message);
        return new JsonResult(StatusCode.OPERATION_FAILED, message);
       }

    @ExceptionHandler
    public JsonResult doHanleThrowable(Throwable ex){
        String message = ex.getMessage();
        log.error("Throwable:" + message);
        return new JsonResult(StatusCode.THROWABLE_ERROR, message);
    }
}
